package com.coding.intercepor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/6/23 22:54:52
 */
@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {


        /*String uri = request.getURI().getPath();
        log.info("ws请求路径: {}", uri);
        if (uri.startsWith("/chat/")) {
            String userId = uri.split("/")[2];
            attributes.put("userId", userId);
            log.info("userId: {}", userId);
        } else if (uri.startsWith("/likews/")) {
            String[] parts = uri.split("/");
            String userId = parts[2];
            String roomId = parts[3];
            attributes.put("userId", userId);
            attributes.put("roomId", roomId);
            log.info("userId: {}, roomId: {}", userId, roomId);
        }
        return true;*/
        String path = request.getURI().getPath();

        log.info("ws请求路径: {}", path);
        Pattern pattern = Pattern.compile("/likews/(\\d+)/(\\d+)");
        Matcher matcher = pattern.matcher(path);

        if (matcher.find()) {
            String userId = matcher.group(1);
            String roomId = matcher.group(2);
            attributes.put("userId", userId);
            attributes.put("roomId", roomId);
            log.info("userId: {}, roomId: {}", userId, roomId);
        }
        return true;

    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {

    }
}


